'use strict';
const db = uniCloud.database()
exports.main = async (event, context) => {
	const user = await db.collection('users').where({
		userId: event.userId
	}).get();

	if (user.affectedDocs === 0) {
		return {
			code: -1,
			message: '用户不存在'
		};
	}
	const currentUser = user.data[0];
	//查找数组tasks中id为1的
	const signInTask = currentUser.tasks.find(task => task.id === 1);
	if (signInTask && !signInTask.isCompleted) {
		// 标记签到任务为已完成
		signInTask.isCompleted = true;

		// 更新用户的积分、经验和任务列表
		currentUser.score += signInTask.value;
		currentUser.levelProgress += 2 * signInTask.value;

		// 检查是否升级
		if (currentUser.levelProgress >= 100) {
			const excessProgress = currentUser.levelProgress - 100; // 计算超过阈值的部分
			currentUser.level += 1;
			currentUser.levelProgress = excessProgress; // 将超过阈值的部分保留
		}

		// 更新用户数据
		await db.collection('users').where({
			userId: event.userId
		}).update({
			tasks: currentUser.tasks,
			score: currentUser.score,
			level: currentUser.level,
			levelProgress: currentUser.levelProgress
		});

	} else { 
		return;
	}

};